package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.github.pagehelper.Page;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PutMapping;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {
    private final OrderMapper orderMapper;//订单表
    private final OrderDetailMapper orderDetailMapper;//订单明细
    private final AddressBookMapper addressBookMapper;//地址
    private final ShoppingCartMapper shoppingCartMapper;//购物车
    private final WeChatPayUtil weChatPayUtil;//工具类
    private final UserMapper userMapper;//用户
    private final WebSocketServer webSocketServer;//ws请求




    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {

        //处理各种异常
        //1.判断地址是否为空
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if(addressBook==null){
            //抛出异常
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //2.检查购物车是否为空
        Long userId = BaseContext.getCurrentId();//获取当前登录用户id
        ShoppingCart shoppingCart = new ShoppingCart();//创建购物车对象，因为查询购物车需要传入购物车对象
        shoppingCart.setUserId(userId);//设置购物车对象的用户id
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);//查询购物车
        if(shoppingCartList==null|| shoppingCartList.isEmpty()){
            //抛出异常
            throw new AddressBookBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //向订单表插入一条数据
        //先构造订单数据
        Orders order = new Orders();//构建订单对象
        BeanUtils.copyProperties(ordersSubmitDTO,order);//拷贝对象
        order.setPhone(addressBook.getPhone());//根据地址手机号插入订单表
        order.setOrderTime(LocalDateTime.now());//设置当前时间
        order.setStatus(Orders.PENDING_PAYMENT);//设置订单状态，刚下单：待付款
        order.setPayStatus(Orders.UN_PAID);//设置支付状态：刚下单：未支付
        order.setUserId(userId);//设置当前微信用户id
        order.setNumber(String.valueOf(System.currentTimeMillis()));//设置订单号
        order.setConsignee(addressBook.getConsignee());//设置收货人
//        order.setAddress(addressBook.getDetail());//设置收获地址
        //向订单表插入1条数据
        orderMapper.insert(order);
        //向订单明细表插入n条数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();//创建订单明细对象
            BeanUtils.copyProperties(cart, orderDetail);//把购物车属性拷贝到订单明细
            orderDetail.setOrderId(order.getId());//设置当前订单明细关联的订单id
            orderDetailList.add(orderDetail);//向订单明细集合插入数据
        }
        //批量插入数据
        orderDetailMapper.insertBatch(orderDetailList);

        //清空当前用户购物车
        shoppingCartMapper.deleteByUserId(userId);//清空当前登录用户的购物车
        //封装返回数据
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()//封装返回对象
                .id(order.getId())//设置id
                .orderTime(order.getOrderTime())//设置订单创建时间
                .orderNumber(order.getNumber())//设置订单号
                .orderAmount(order.getAmount())//总金额
                .build();
        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
        //生成空JSON，跳过微信支付
        JSONObject jsonObject=new JSONObject();

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }


    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //通过webosocket向客服端浏览器推送消息 type ordeerId content
        Map map=new HashMap();
        map.put("type",1);//1.表示来单提醒 2表示客服催单
        map.put("orderId",ordersDB.getId());//获得订单id
        map.put("content","订单号："+outTradeNo);//提示内容
        //map转json
        String json = JSON.toJSONString(map);//获得json字符串
        //推送到控制台页面
        webSocketServer.sendToAllClient(json);
    }

    /**
     *历史订单查询
     * @param pageNum
     * @param pageSize
     * @param status
     * @return
     */
    public PageResult pageQuery(int pageNum, int pageSize, Integer status) {
        // 设置分页
        PageHelper.startPage(pageNum, pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        // 分页条件查询订单数据
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);//MyBatis会根据查询结果自动将数据库表中的字段映射到 Orders 对象的属性中
        //每条订单数据都会映射为一个 Orders 对象。
        List<OrderVO> list = new ArrayList();

        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                Long orderId = orders.getId();// 订单id

                // 查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), list);
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO details(long id) {
        // 根据id查询订单
        Orders orders = orderMapper.getById(id);

        // 查询该订单对应的菜品/套餐明细
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将该订单及其详情封装到OrderVO并返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);//尽管属性名不匹配，但是因为orderVo继承了orders，所以才能拷贝成功
        orderVO.setOrderDetailList(orderDetailList);

        return orderVO;
    }


    /**
     * 取消订单
     * @param id
     */
    @Override
    @Transactional
    public void update(long id) {
    //根据传入的用户id修改订单状态为：取消
        Orders orders = new Orders();
        orders.setStatus(6);
        orders.setId(id);
        orderMapper.update(orders);
    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    public void repetitionOrders(long id) {
        //1.根据订单id从订单详情表中拿出菜品集合
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        for (OrderDetail orderDetail : orderDetailList) {

            ShoppingCart shoppingCart = new ShoppingCart();//购物车对象
            if (orderDetail.getDishId()!=null){//判断是否菜品
                shoppingCart.setDishId(orderDetail.getDishId());//设置菜品id
            }else {
                shoppingCart.setSetmealId(orderDetail.getSetmealId());//设置套餐id
            }
            shoppingCart.setDishFlavor(orderDetail.getDishFlavor());//设置口味
            shoppingCart.setUserId(BaseContext.getCurrentId());//设置用户id
            shoppingCart.setName(orderDetail.getName());//设置菜品或套餐名称
            shoppingCart.setImage(orderDetail.getImage());//设置菜品或套餐图片
            shoppingCart.setNumber(orderDetail.getNumber());//设置菜品或套餐数量
            shoppingCart.setAmount(orderDetail.getAmount());//设置菜品或套餐金额
            shoppingCart.setCreateTime(LocalDateTime.now());//设置菜品或套餐时间
            //3.加入购物车
            shoppingCartMapper.insert(shoppingCart);
        }


    }

    /**
     * 订单搜索
     *
     * @param ordersPageQueryDTO
     * @return
     */
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        // 部分订单状态，需要额外返回订单菜品信息，将Orders转化为OrderVO
        List<OrderVO> orderVOList = getOrderVOList(page);

        return new PageResult(page.getTotal(), orderVOList);
    }

    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        // 需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();

        List<Orders> ordersList = page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {
                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                String orderDishes = getOrderDishesStr(orders);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;
    }

    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO statisSum() {
        // 根据状态，分别查询出待接单、待派送、派送中的订单数量
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);
        // 将查询出的数据封装到orderStatisticsVO中响应
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    @Transactional
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();
        orderMapper.update(orders);
    }

    /**
     * 拒单
     * @param ordersCancelDTO
     */
    @Override
    @Transactional
    public void rejection(OrdersCancelDTO ordersCancelDTO){

        Orders orders = Orders.builder()
                .id(ordersCancelDTO.getId())
                .status(Orders.CANCELLED)
                .cancelReason(ordersCancelDTO.getCancelReason())
                .cancelTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    @Transactional
    public void delivery(long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 校验订单是否存在，并且状态为3
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为派送中
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);

        orderMapper.update(orders);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 校验订单是否存在，并且状态为4
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为完成
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(ordersCancelDTO.getId());

        // 校验订单是否存在，并且状态为未完成
        if (ordersDB != null && !ordersDB.getStatus().equals(Orders.COMPLETED)) {
            Orders orders = Orders.builder()
                    .id(ordersCancelDTO.getId())
                    .status(Orders.CANCELLED)
                    .cancelReason(ordersCancelDTO.getCancelReason())
                    .cancelTime(LocalDateTime.now())
                    .build();
            orderMapper.update(orders);
        }
        else {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR2);
        }
    }

    /**
     * 客服催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 校验订单是否存在，并且状态为2
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //通过webosocket向客服端浏览器推送消息 type ordeerId content
        Map map=new HashMap();
        map.put("type",2);//1.表示来单提醒 2表示客服催单
        map.put("orderId",id);//获得订单id
        map.put("content","订单号："+ordersDB.getNumber());//提示内容
        //map转json
        String json = JSON.toJSONString(map);//获得json字符串
        //推送到控制台页面
        webSocketServer.sendToAllClient(json);

    }
}
